package com.tenglong.teacher.ui.homepage;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.content.FileProvider;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.cuotibao.zhuoxiao.basics.GlobalConstant;
import com.cuotibao.zhuoxiao.basics.utils.DensityUtil;
import com.cuotibao.zhuoxiao.basics.utils.ToastUtils;
import com.cuotibao.zhuoxiao.basics.utils.file.UriToPathUtil;
import com.google.gson.Gson;
import com.tenglong.teacher.BuildConfig;
import com.tenglong.teacher.R;
import com.tenglong.teacher.data.resultInfo.DataState;
import com.tenglong.teacher.data.resultInfo.SeClass;
import com.tenglong.teacher.data.resultInfo.StudentSignBottomInfo;
import com.tenglong.teacher.data.resultInfo.BaseStudentSignInfo;
import com.tenglong.teacher.data.resultInfo.StudentSignHeaderInfo;
import com.tenglong.teacher.data.resultInfo.StudentSignInfo;
import com.tenglong.teacher.data.resultInfo.base.BaseResult;
import com.tenglong.teacher.data.resultInfo.base.ResultVerifier;
import com.tenglong.teacher.services.hdx.CreateRequestEntity;
import com.tenglong.teacher.ui.adapter.StudentAdapter;
import com.tenglong.teacher.ui.common.activity.BaseActivity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class StudentSignActivity extends BaseActivity implements StudentAdapter.StudentListener {

    public static final String KEY_DAYA = StudentSignActivity.class.getCanonicalName() + "key_data";
    /**
     * 班课信息数组
     */
    private List<BaseStudentSignInfo> studentSignInfos;
    /**
     * 上个界面传递过来的班级信息
     */
    private SeClass data;
    /**
     * 是否显示批量操作布局
     */
    private boolean isShowCheckAllLayout = false;
    /**
     * 是否全部选中
     */
    private boolean isCheckAll = false;
    /**
     * 底部布局
     */
    private View bottomLayout;
    /**
     * 是否全选按钮
     */
    private View tv_checkAll;
    /**
     * 展示布局容器
     */
    private RecyclerView recyclerView;
    /**
     * 适配器
     */
    private StudentAdapter mAdapter;

    /**
     * 课堂id
     */
    private String classRecordId;

    /**
     * 点击的item位置
     */
    private int clickPosition = -1;

    /**
     * 当前是什么类型key
     */
    public static final String KEY_CURRENT_TYPE = "key_current_type";

    /**
     * 当前是什么类型(==2,为一对一；==1，我的班课)
     */
    public String classType = FragmentHompage.TYPE_ALL_CLASS;
    /**
     * 拍张图片地址
     */
    private String path;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_student_sign);
        data = (SeClass) getIntent().getSerializableExtra(KEY_DAYA);
        classType = getIntent().getStringExtra(KEY_CURRENT_TYPE);
        initView();
        initRecy();
        setAdapter();
        setListeners();
        requestData();
    }


    private void initView() {
        setTitle(classType.equals(FragmentHompage.TYPE_ALL_CLASS) ? "我的班课" : "我的一对一");
        recyclerView = findViewById(R.id.recyclerView);
        bottomLayout = findViewById(R.id.bottomLayout);
        tv_checkAll = findViewById(R.id.tv_checkAll);
    }

    private void initRecy() {
        ((GridLayoutManager) recyclerView.getLayoutManager()).setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                if (studentSignInfos != null) {
                    if (studentSignInfos.get(position) instanceof StudentSignHeaderInfo) {
                        return 2;
                    } else return 1;
                } else {
                    return 1;
                }
            }
        });
        recyclerView.setHasFixedSize(true);
        recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                int index = parent.getChildAdapterPosition(view);
                int t = DensityUtil.dp2px((float) 18.666);
                int r = DensityUtil.dp2px((float) 9.333);
                if (studentSignInfos != null) {
                    if (studentSignInfos.size() > 0) {
                        if (studentSignInfos.get(0) instanceof StudentSignHeaderInfo) {
                            if (index == 0) {
                                outRect.top = t;
                                outRect.left = t;
                                outRect.right = t;
                            } else {
                                if (classType.equals(FragmentHompage.TYPE_ONE_TO_ONE)) {
                                    if (index == 1 || index == 2) {
                                        outRect.top = t;
                                    }
                                } else {
                                    if (index != 1 && index != 2) {
                                        outRect.top = t;
                                    }
                                }
                                if (index % 2 == 1) {
                                    outRect.left = t;
                                    outRect.right = r;
                                } else {
                                    outRect.left = r;
                                    outRect.right = t;
                                }
                            }
                        } else {
                            outRect.top = t;
                            if (index % 2 == 0) {
                                outRect.left = t;
                                outRect.right = r;
                            } else {
                                outRect.left = r;
                                outRect.right = t;
                            }
                        }
                        if (studentSignInfos.size() == 1) {
                            outRect.bottom = t;
                        } else if (studentSignInfos.size() == 2) {
                            if (studentSignInfos.get(0) instanceof StudentSignHeaderInfo) {
                                if (index == 1) {
                                    outRect.bottom = t;
                                }
                            } else {
                                outRect.bottom = t;
                            }
                        } else if (studentSignInfos.size() == 3) {
                            if (studentSignInfos.get(0) instanceof StudentSignHeaderInfo) {
                                if (index == 1 || index == 2) {
                                    outRect.bottom = t;
                                }
                            } else {
                                if (index == 2) {
                                    outRect.bottom = t;
                                }
                            }
                        } else {
                            if (studentSignInfos.get(0) instanceof StudentSignHeaderInfo) {
                                if ((studentSignInfos.size() - 1) % 2 == 0) {
                                    if ((studentSignInfos.size() - 1 == index) || studentSignInfos.size() - 2 == index) {
                                        outRect.bottom = t;
                                    }
                                } else {
                                    if (studentSignInfos.size() - 1 == index) {
                                        outRect.bottom = t;
                                    }
                                }
                            } else {
                                if ((studentSignInfos.size() - 1) % 2 == 1) {
                                    if ((studentSignInfos.size() - 1 == index) || studentSignInfos.size() - 2 == index) {
                                        outRect.bottom = t;
                                    }
                                } else {
                                    if (studentSignInfos.size() - 1 == index) {
                                        outRect.bottom = t;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        });
    }

    private void setListeners() {
        tv_checkAll.setOnClickListener(this);
        mAdapter.setOnItemStudentListener(this);
        findViewById(R.id.tvAllSign).setOnClickListener(this);
    }

    private void setAdapter() {
        studentSignInfos = new ArrayList<>();
        mAdapter = new StudentAdapter(studentSignInfos);
        recyclerView.setAdapter(mAdapter);
    }


    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.tv_checkAll:
                if (studentSignInfos == null || studentSignInfos.size() < 1) return;
                isCheckAll = !isCheckAll;
                boolean isCanAllSign = false;
                for (BaseStudentSignInfo info : studentSignInfos) {
                    if (info instanceof StudentSignBottomInfo) {
                        if (((StudentSignBottomInfo) info).type == 0) {
                            ((StudentSignBottomInfo) info).isSele = isCheckAll;
                            isCanAllSign = true;
                            mAdapter.notifyItemChanged(studentSignInfos.indexOf(info));
                        }
                    }
                }
                tv_checkAll.setSelected(isCanAllSign ? isCheckAll : false);
                if (!isCanAllSign) {
                    isCheckAll = false;
                    ToastUtils.showCenterToast("没有可签到的学生");
                }
                break;
            case R.id.tvAllSign:
                allSign();
                break;
        }
    }

    private void requestData() {
        showProgressDialog("数据访问中...");
        CreateRequestEntity.getWebService().getStudentRecordByClassId(data.getId()).enqueue(new Callback<BaseResult<StudentSignInfo>>() {
            @Override
            public void onResponse(Call<BaseResult<StudentSignInfo>> call, Response<BaseResult<StudentSignInfo>> response) {
                dismissProgressDialog();
                if (ResultVerifier.isSucceed(response)) {
                    studentSignInfos.clear();
                    if (response.body().data.classRecord != null) {
                        response.body().data.classRecord.isHeader = true;
                        response.body().data.classRecord.isClassBeing = response.body().data.classRecord.classStartTime != null;
                        response.body().data.classRecord.submitCount = response.body().data.submitCount;
                        response.body().data.classRecord.homeWorkStatu = response.body().data.homeWorkStatu;
                        classRecordId = response.body().data.classRecord.id;
                        studentSignInfos.add(response.body().data.classRecord);
                        if (response.body().data.seStudent != null) {
                            for (StudentSignBottomInfo info : response.body().data.seStudent) {
                                info.classRecordId = response.body().data.classRecord.id;
                                info.isClassBeing = response.body().data.classRecord.isClassBeing;
                                info.isSign = info.type != 0;
                                info.isEvaluate = !TextUtils.isEmpty(info.classShapeImg) || !TextUtils.isEmpty(info.classShapeText) || !TextUtils
                                        .isEmpty(info.classShapeVideo) || info.classPerformanceEvaluation > 0;
                                info.homeWorkStatu = response.body().data.homeWorkStatu;
                                info.submitCount = response.body().data.submitCount;
                            }
                            studentSignInfos.addAll(response.body().data.seStudent);
                            boolean state = getSignState();
                            for (BaseStudentSignInfo studentSignInfo : studentSignInfos) {
                                studentSignInfo.isAllStudentSign = state;
                            }
                        }
                        mAdapter.notifyDataSetChanged();
                        if (response.body().data.classRecord.isClassBeing) {
                            getHomeWorkState();
                        }
                    }
                } else {
                    ToastUtils.showCenterToast(ResultVerifier.serceErrers(response));
                }
            }

            @Override
            public void onFailure(Call<BaseResult<StudentSignInfo>> call, Throwable t) {
                dismissProgressDialog();
                ResultVerifier.systerErrers(t);
            }
        });
    }


    private void getHomeWorkState() {
        CreateRequestEntity.getWebService().getClassHomeworkIsPublish(data.getId()).enqueue(new Callback<BaseResult<Boolean>>() {
            @Override
            public void onResponse(Call<BaseResult<Boolean>> call, Response<BaseResult<Boolean>> response) {
                if (ResultVerifier.isSucceed(response)) {
                    if (studentSignInfos != null) {
                        for (BaseStudentSignInfo info : studentSignInfos) {
                            info.isHomeWorkState = response.body().data;
                        }
                    }
                } else {
                    ToastUtils.showCenterToast(ResultVerifier.serceErrers(response));
                }
            }

            @Override
            public void onFailure(Call<BaseResult<Boolean>> call, Throwable t) {
                ResultVerifier.systerErrers(t);
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case GlobalConstant.REQUEST_CODE_CLASS_ROOM:
                    if (clickPosition != -1) {
                        ((StudentSignBottomInfo) studentSignInfos.get(clickPosition)).isEvaluate = true;
                    }
                    break;
                case GlobalConstant.REQUEST_CODE_SHOOT:
                    if (path == null || path.equals("")) return;
                    uploadPaperCertificate(new File(path));
                    break;
                case GlobalConstant.REQUEST_CODE_GAINT_PHOTO:
                    if (data != null) {
                        Uri imageUri = data.getData();
                        if (imageUri == null) return;
                        uploadPaperCertificate(new File(UriToPathUtil.getImageAbsolutePath(this, imageUri)));
                    }
                    break;
                case GlobalConstant.REQUEST_CODE_PUBLISH_HOMEWORK_ACTIVITY:
                    ((StudentSignHeaderInfo) studentSignInfos.get(0)).isHomeWorkState = true;
                    break;
            }
        }
    }

    private void uploadPaperCertificate(File file) {
        showProgressDialog("图片上传中...");
        RequestBody photoBody =
                RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part photoPart = MultipartBody.Part.createFormData("affirmImg", file.getName(), photoBody);
        CreateRequestEntity.getWebService().upLoadPaperCertificate(classRecordId, ((StudentSignBottomInfo) studentSignInfos.get(1)).id, photoPart).enqueue(new Callback<BaseResult<String>>() {
            @Override
            public void onResponse(Call<BaseResult<String>> call, Response<BaseResult<String>> response) {
                dismissProgressDialog();
                if (ResultVerifier.isSucceed(response)) {
                    toClassOver();
                } else {
                    ToastUtils.showCenterToast(ResultVerifier.serceErrers(response));
                }
            }

            @Override
            public void onFailure(Call<BaseResult<String>> call, Throwable t) {
                dismissProgressDialog();
                ResultVerifier.systerErrers(t);
            }
        });
    }

    public void allSign() {
        SignInfo param = getRequestParam();
        if (param.Signed.size() == 0 && param.lated.size() == 0) {
            ToastUtils.showCenterToast("没有可签到的学生");
            return;
        }
        showProgressDialog("正在访问,请稍后...");
        CreateRequestEntity.getWebService().batchStudentSign(new Gson().toJson(param), "2", classRecordId).enqueue(new Callback<BaseResult<String>>() {
            @Override
            public void onResponse(Call<BaseResult<String>> call, Response<BaseResult<String>> response) {
                if (ResultVerifier.isSucceed(response)) {
                    for (BaseStudentSignInfo info : studentSignInfos) {
                        if (info instanceof StudentSignBottomInfo) {
                            if (((StudentSignBottomInfo) info).isSele) {
                                ((StudentSignBottomInfo) info).type = 2;
                                ((StudentSignBottomInfo) info).isSele = false;
                                ((StudentSignBottomInfo) info).isShowCircleQuan = false;
                            } else {
                                if (((StudentSignBottomInfo) info).type == 0) {
                                    ((StudentSignBottomInfo) info).type = 8;
                                    ((StudentSignBottomInfo) info).isSele = false;
                                    ((StudentSignBottomInfo) info).isShowCircleQuan = false;
                                }
                            }
                        }
                        info.isAllStudentSign = true;
                    }
                    isCheckAll = false;
                    isShowCheckAllLayout = false;
                    tv_checkAll.setSelected(false);
                    bottomLayout.setVisibility(View.GONE);
                    mAdapter.notifyDataSetChanged();
                    refreshPeopleNum();
                } else {
                    ToastUtils.showCenterToast(ResultVerifier.serceErrers(response));
                }
                dismissProgressDialog();
            }

            @Override
            public void onFailure(Call<BaseResult<String>> call, Throwable t) {
                ResultVerifier.systerErrers(t);
                dismissProgressDialog();
            }
        });
    }

    @Override
    public void onBatchOperation(int position) {
        if (studentSignInfos != null) {
            if (studentSignInfos.size() > 0 && !studentSignInfos.get(0).isClassBeing) {
                ToastUtils.showCenterToast("上课后才能签到");
                return;
            }
            if (studentSignInfos == null || studentSignInfos.size() < 1) return;
            if (studentSignInfos.get(0).isAllStudentSign) {
                ToastUtils.showCenterToast("已完成签到");
                return;
            }
            isShowCheckAllLayout = !isShowCheckAllLayout;
            for (BaseStudentSignInfo info : studentSignInfos) {
                if (info instanceof StudentSignBottomInfo) {
                    if (((StudentSignBottomInfo) info).type == 0) {
                        ((StudentSignBottomInfo) info).isShowCircleQuan = isShowCheckAllLayout;
                        ((StudentSignBottomInfo) info).isSele = false;
                        mAdapter.notifyItemChanged(studentSignInfos.indexOf(info));
                    }
                }
            }
            isCheckAll = false;
            tv_checkAll.setSelected(false);
            bottomLayout.setVisibility(isShowCheckAllLayout ? View.VISIBLE : View.GONE);
        }
    }

    @Override
    public String getClassId() {
        if (data != null) {
            return data.getId();
        } else return "";
    }

    @Override
    public void refreshPeopleNum() {
        if (studentSignInfos != null) {
            int peopleNum = 0;
            for (BaseStudentSignInfo info : studentSignInfos) {
                if (info instanceof StudentSignBottomInfo) {
                    if (((StudentSignBottomInfo) info).type == 2) {
                        peopleNum += 1;
                    }
                }
            }
            ((StudentSignHeaderInfo) studentSignInfos.get(0)).attendance = peopleNum;
            mAdapter.notifyItemChanged(0);
        }
    }

    @Override
    public void onClickClassBegin(int position, boolean isClassBegin) {
        for (BaseStudentSignInfo info : studentSignInfos) {
            info.isClassBeing = isClassBegin;
        }
    }

    @Override
    public void onRecordPosition(int position) {
        clickPosition = position;
    }

    @Override
    public String getClassType() {
        return classType;
    }

    @Override
    public void toPhotoAlbum() {
        Intent intent = new Intent(
                Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, GlobalConstant.REQUEST_CODE_GAINT_PHOTO);
    }

    @Override
    public void toShoot() {
        path = Environment.getExternalStorageDirectory() + "/cuoTiBao/" + System.currentTimeMillis() + ".jpg";
        File f = new File(path);
        if (!f.getParentFile().exists()) {
            f.getParentFile().mkdir();
        }
        Uri imageUri = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".fileprovider", f);//这里进行替换uri的获得方式
        Intent intent = new Intent();
        intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        startActivityForResult(intent, GlobalConstant.REQUEST_CODE_SHOOT);
    }

    @Override
    public boolean getSignState() {
        if (studentSignInfos != null) {
            for (BaseStudentSignInfo studentSignInfo : studentSignInfos) {
                if (studentSignInfo instanceof StudentSignBottomInfo) {
                    int type = ((StudentSignBottomInfo) studentSignInfo).type;
                    if (type == 0) {
                        return false;
                    }
//                    return type == 2 || type == 1 || type == 8 || type == 7 || type == 5 || type == 3 || type == 4;
                }
            }
        }
        return true;
    }

    @Override
    public void getPublishHomeWorkState() {
        getHomeWorkState();
    }

    public SignInfo getRequestParam() {
        SignInfo signInfo = new SignInfo();
        if (studentSignInfos != null) {
            List<String> signed = new ArrayList<>();
            List<String> lated = new ArrayList<>();
            for (BaseStudentSignInfo info : studentSignInfos) {
                if (info instanceof StudentSignBottomInfo) {
                    if (((StudentSignBottomInfo) info).isSele) {
                        signed.add(((StudentSignBottomInfo) info).id);
                    } else {
                        if (((StudentSignBottomInfo) info).type == 0) {
                            lated.add(((StudentSignBottomInfo) info).id);
                        }
                    }
                }
            }
            signInfo.Signed = signed;
            signInfo.lated = lated;
        }
        return signInfo;
    }


    private void toClassOver() {
        showProgressDialog("正在访问,请稍后...");
        CreateRequestEntity.getWebService().classOverOrUp(classRecordId, "1", DataState.getInstance().getUserInfo().getId()).enqueue(new Callback<BaseResult<String>>() {
            @Override
            public void onResponse(Call<BaseResult<String>> call, Response<BaseResult<String>> response) {
                dismissProgressDialog();
                if (ResultVerifier.isSucceed(response)) {
                    setResult(Activity.RESULT_OK, new Intent().putExtra(GlobalConstant.RESULT_CODE_STUDENT_SIGN_ACTIVITY, false));
                    finish();
                } else {
                    ToastUtils.showCenterToast(ResultVerifier.serceErrers(response));
                }
            }

            @Override
            public void onFailure(Call<BaseResult<String>> call, Throwable t) {
                dismissProgressDialog();
                ResultVerifier.systerErrers(t);
            }
        });
    }

    class SignInfo {
        public List<String> Signed;
        public List<String> lated;
    }

}
